import 'dart:io';
import 'dart:ui' as ui;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'magic_svga.dart';

/// 图片类型
enum ImgType {
  /// png 格式
  png,

  /// svga 格式
  svga,
}

extension ImgTypeRawValue on ImgType {
  static ImgType? from(String? rawValue) {
    switch (rawValue) {
      case 'png':
        return ImgType.png;
      case 'svga':
        return ImgType.svga;
      default:
        return null;
    }
  }

  String get rawValue {
    switch (this) {
      case ImgType.png:
        return 'png';
      case ImgType.svga:
        return 'svga';
    }
  }
}

abstract class MagicImage {
  /// 默认头像 本地图片名
  static String get defaultAvatarName => 'default_avatar';

  /// 默认头像
  static Image get defaultAvatar => image(defaultAvatarName);

  /// 黑色返回
  static Image get back => image('icon_back');

  /// 白色返回
  static Image get whiteBack => image('icon_back_white');

  /// 弹窗 灰色 关闭
  static Image get popupClose => image('close_circle_31_grey');

  /// 便利获取 AssetImage 的方法，避免需要输入 assets/images/。
  ///
  /// @{tool-snippet}
  /// ```dart
  /// final assetImage1 = MagicImage.assetImage('image_name');
  /// final assetImage2 = MagicImage.assetImage('home_bg', ext: 'jpg');
  /// ```
  /// @{end-tool}
  static AssetImage assetImage(
    String name, {
    String ext = 'png',
  }) {
    return AssetImage('assets/images/$name.$ext');
  }

  /// 直接读取文件。
  ///
  /// @{tool-snippet}
  /// ```dart
  /// final image1 = MagicImage.image('image_name');
  /// final image2 = MagicImage.image('home_bg', ext: 'jpg', width: 375, height: 44);
  /// ```
  /// @{end-tool}
  static Image fileImage(
    File name, {
    Key? key,
    String ext = 'png',
    double? width,
    double? height,
    BoxFit? fit,
    AlignmentGeometry alignment = Alignment.center,
  }) =>
      Image.file(
        name,
        key: key,
        width: width,
        height: height,
        fit: fit,
        alignment: alignment,
      );

  /// 便利获取 Image 的方法，避免需要输入 assets/images/。
  ///
  /// @{tool-snippet}
  /// ```dart
  /// final image1 = MagicImage.image('image_name');
  /// final image2 = MagicImage.image('home_bg', ext: 'jpg', width: 375, height: 44);
  /// ```
  /// @{end-tool}
  static Image image(
    String name, {
    Key? key,
    String folder = 'images',
    String ext = 'png',
    double? width,
    double? height,
    BoxFit? fit,
    AlignmentGeometry alignment = Alignment.center,
    Color? color,
    BlendMode? colorBlendMode,
  }) =>
      Image.asset(
        'assets/$folder/$name.$ext',
        key: key,
        width: width,
        height: height,
        fit: fit,
        alignment: alignment,
        color: color,
        colorBlendMode: colorBlendMode,
      );

  /// 带边框的网络图片加载。
  ///
  /// [placeholder] 相对路径 本地默认图片；
  /// [decoration] 自定义图片形状（如 shapeDecoration）；
  /// [fit] 图片样式；
  static Widget networkBorderImage(
    String path, {
    Border? border,
    BorderRadius? borderRadius,
    Decoration? decoration,
    String? placeholder,
    double? width,
    double? height,
    BoxFit? fit,
  }) {
    return Container(
      decoration: decoration ?? BoxDecoration(border: border, borderRadius: borderRadius),
      child: ClipRRect(
        borderRadius: borderRadius ?? BorderRadius.zero,
        child: networkImage(
          path,
          placeholder: placeholder,
          width: width,
          height: height,
          fit: fit,
        ),
      ),
    );
  }

  /// 网络图片加载。
  ///
  /// [placeholder] 图片占位，本地图片名。
  /// [fit] 图片样式。
  /// [alignment] 控制图片不满高度时的位置
  static Widget networkImage(
    String? path, {
    String? placeholder,
    Color? placeholderColor,
    double? width,
    double? height,
    BoxFit? fit,
    Alignment? alignment,
    Color? color,
    BlendMode? colorBlendMode,
    ImgType? imgType = ImgType.png,
  }) {
    Widget placeholderWidget() {
      if (placeholder == null || placeholder.isEmpty) {
        return Container(width: width, height: height, color: placeholderColor);
      }
      return image(placeholder, width: width, height: height, fit: fit);
    }

    if (path == null || path.isEmpty) {
      return placeholderWidget();
    }

    if (imgType == ImgType.svga || path.endsWith('.svga')) {
      return MagicSvga(url: path, width: width, height: height);
    }

    return CachedNetworkImage(
      width: width,
      height: height,
      placeholder: (context, url) => placeholderWidget(),
      errorWidget: (context, url, error) => placeholderWidget(),
      fit: fit,
      alignment: alignment ?? Alignment.center,
      color: color,
      colorBlendMode: colorBlendMode,
      imageUrl: path,
    );
  }

  ///获取本地图片流数据
  static Future<ui.Image> getAssetUiImage(
    String path, {
    String ext = 'png',
  }) async {
    ByteData data = await rootBundle.load('assets/images/$path.$ext');
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo frameInfo = await codec.getNextFrame();
    return frameInfo.image;
  }
}
